package org.sws.domain.activity.service.armory;

import org.springframework.stereotype.Service;
import org.sws.domain.activity.model.entity.ActivitySkuEntity;
import org.sws.domain.activity.repository.IActivityRepository;
import org.sws.types.common.Constants;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author sws
 * @Date 2025/3/19 16:23
 * @description: 抽奖活动装配调度实现类
 */
@Service
public class ActivityArmory implements IActivityArmory, IActivityDispatch{

    @Resource
    private IActivityRepository activityRepository;

    @Override
    public boolean assembleActivitySku(Long sku) {
        // 预热活动sku库存
        ActivitySkuEntity activitySkuEntity = activityRepository.queryActivitySku(sku);
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_SURPLUS_KEY + sku;
        activityRepository.cacheActivitySkuStockCount(cacheKey, activitySkuEntity.getStockCountSurplus() == 0? activitySkuEntity.getStockCount() : activitySkuEntity.getStockCountSurplus());
        // 预热活动【查询时预热到缓存】
        activityRepository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());
        // 预热活动次数【查询时预热到缓存】
        activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        return true;
    }

    @Override
    public void assembleActivitySkuByActivityId(Long activityId) {
       List<ActivitySkuEntity> activitySkuEntityList = activityRepository.queryActivitySkuByActivityId(activityId);
       for (ActivitySkuEntity activitySkuEntity : activitySkuEntityList) {
           // 缓存sku剩余库存
           String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_SURPLUS_KEY + activitySkuEntity.getSku();
           activityRepository.cacheActivitySkuStockCount(cacheKey, activitySkuEntity.getStockCountSurplus());
           // 缓存活动参与次数
           activityRepository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
       }
       // 缓存活动信息
       activityRepository.queryRaffleActivityByActivityId(activityId);
    }

    @Override
    public boolean subtractSkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_SURPLUS_KEY + sku;
        return activityRepository.subtractSkuStock(sku, cacheKey , endDateTime);
    }
}
